/**
 * ©2009-2018 南京擎盾信息科技有限公司 All rights reserved.
 */
package com.wuhao.code.check.inspection.visitor

import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.lang.Language
import com.intellij.psi.PsiElement
import com.wuhao.code.check.actualType
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.nj2k.postProcessing.resolve
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtUserType
import org.jetbrains.kotlin.psi.KtVisitor
import org.jetbrains.kotlin.psi.psiUtil.containingClass

/**
 * kotlin代码格式检查访问器
 * Created by 吴昊 on 18/4/26.
 *
 * @author 吴昊
 * @since 1.1
 */
class KotlinActionSpecificationVisitor(private val holder: ProblemsHolder) : KtVisitor<Unit, Any>(), BaseCodeFormatVisitor {

  override fun support(language: Language): Boolean {
    return language == KotlinLanguage.INSTANCE
  }

  override fun visitNamedFunction(fn: KtNamedFunction, data: Any?) {
    val modelType = getXmllessMapperModelType(fn)
    if (modelType != null && modelType is KtClass) {
      holder.registerProblem(
          fn,
          "[XMLLess]：生成脚本并在对话框中打卡",
          ProblemHighlightType.INFORMATION,
          XmllessGeneratorInDialog()
      )
      holder.registerProblem(
          fn,
          "[XMLLess]：生成脚本并在编辑器中打卡",
          ProblemHighlightType.INFORMATION,
          XmllessGeneratorInEditor()
      )
    }

    return super.visitNamedFunction(fn, data)
  }

}


/**
 * @param fn
 * @return
 */
fun getXmllessMapperModelType(fn: KtNamedFunction): PsiElement? {
  val clazz = fn.containingClass()
  clazz?.superTypeListEntries?.forEach {
    val el = it.typeReference?.typeElement?.actualType
    if (el is KtUserType) {
      val ref = el.referenceExpression?.text
      if (ref == "XmlLessMapper" && el.typeArguments.isNotEmpty()) {
        val typeEl = el.typeArguments[0].typeReference?.typeElement
        if (typeEl is KtUserType) {
          return typeEl.referenceExpression?.resolve()
        }
      }
    }
  }
  return null
}
